<template>
  <div class="createApplication">
    <div class="create-appImage">
      <span>创建应用包镜像<span class="return" @click="goback">&lt;&nbsp;返回</span></span>
    </div>
    <div class="appImageMsg">
      <el-form ref="createApplication" :model="application.data" label-width="140px" label-position="left" :rules="rules" :scroll-to-error="true">
        <div class="title">
          <div class="title-label"></div>
          基本信息
        </div>
        <div class="formData">
          <el-form-item prop="request.name" :rules="rules.name">
            <template #label>
              <div class="item-label">应用包名</div>
            </template>
            <el-input v-model="application.data.request.name" maxlength="50" minlength="1" placeholder="应用包将会在路径”/local/app/{应用包名}“ 下解压" />
          </el-form-item>
          <el-form-item prop="request.version" :rules="rules.version">
            <template #label>
              <div class="item-label">版本号</div>
            </template>
            <el-input v-model="application.data.request.version" maxlength="50" />
          </el-form-item>
          <div class="description">
            <el-form-item prop="request.description">
              <template #label>
                <div class="item-label">描述</div>
              </template>
              <el-input :rows="2" type="textarea" v-model="application.data.request.description" maxlength="1024" show-word-limit />
            </el-form-item>
          </div>
          <div class="chooseCreationMethod">
            <span>应用包类型</span>
            <el-radio-group class="radios" v-model="buildType">
              <el-radio-button label="0">VM</el-radio-button>
              <el-radio-button label="1">POD</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <el-divider />
        <div>
          <div class="title">
            <div class="title-label"></div>
            配置资源信息
          </div>
          <div class="formData">
            <div class="chooseCreationMethod">
              <span>创建方式</span>
              <el-radio-group class="radios" v-model="creationMethod">
                <el-radio-button label="1">通过上传文件创建</el-radio-button>
                <el-radio-button label="2">通过obs创建</el-radio-button>
                <el-radio-button label="3">通过已有镜像创建</el-radio-button>
              </el-radio-group>
            </div>
            <div v-if="creationMethod != '3'">
              <el-form-item prop="request.vpc_id" :rules="rules.vpc_id">
                <template #label>
                  <div class="item-label">VPC</div>
                  <el-tooltip effect="dark" content="建议您选择fleetmanager所在的VPC与子网，防止可用ip不足" placement="bottom">
                    <el-icon><QuestionFilled /></el-icon
                  ></el-tooltip>
                </template>
                <el-select
                  v-model="application.data.request.vpc_id"
                  class="m-2 fleet"
                  @change="vpcChange"
                  clearable
                  filterable
                  placeholder="请输入VPC名称进行筛选"
                >
                  <el-option v-for="item in vpcOptions" :key="item.value" :label="item.label" :value="item.value">
                    <div class="fleetLabel">{{ item.label }}</div>
                    <div class="fleetValue">{{ item.value }}</div>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="request.subnet_id" :rules="rules.subnet_id">
                <template #label>
                  <div class="item-label">子网</div>
                </template>
                <el-select v-model="application.data.request.subnet_id" class="m-2 fleet" clearable filterable placeholder="请输入子网名称进行筛选">
                  <el-option v-for="item in subnetOptions" :key="item.value" :label="item.label" :value="item.value">
                    <div class="fleetLabel">{{ item.label }}</div>
                    <div class="fleetValue">{{ item.value }}</div>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="request.bandwidth.size" :rules="rules.bandwidth">
                <template #label>
                  <div class="item-label">带宽大小</div>
                  <el-tooltip effect="dark" content="应用队列单实例公网出带宽最大值，默认1，范围1-2000，单位Mbps" placement="bottom"
                    ><el-icon><QuestionFilled /></el-icon
                  ></el-tooltip>
                </template>
                <el-input v-model.number="application.data.request.bandwidth.size" placeholder="单位：Mbps" />
              </el-form-item>
              <el-form-item prop="request.bandwidth.charging_mode" :rules="rules.charging_mode">
                <template #label>
                  <div class="item-label">带宽计费方式</div>
                  <el-tooltip effect="dark" content="带宽的计费方式" placement="bottom"
                    ><el-icon><QuestionFilled /></el-icon
                  ></el-tooltip>
                </template>
                <el-select v-model="application.data.request.bandwidth.charging_mode" clearable>
                  <el-option label="按流量计费" value="traffic" />
                  <el-option label="按带宽计费" value="bandwidth" />
                </el-select>
              </el-form-item>

              <el-form-item prop="request.enterprise_project">
                <template #label>
                  <div class="item-label">企业项目ID</div>
                </template>
                <el-input v-model="application.data.request.enterprise_project" maxlength="64" minlength="1" />
              </el-form-item>
              <el-form-item prop="request.operating_system" v-if="buildType != '0'" :rules="rules.operating_system">
                <template #label>
                  <div class="item-label">基础镜像</div>
                </template>
                <el-select v-model="application.data.request.operating_system" clearable>
                  <el-option v-for="item in dockerImages" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item prop="request.organization" v-if="buildType != '0'" :rules="rules.organization">
                <template #label>
                  <div class="item-label">指定组织</div>
                </template>
                <el-select v-model="application.data.request.organization" placeholder="请选择指定组织" filterable>
                  <el-option v-for="item in organizationsGroup" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <div class="icon-outbox">
                  <div class="newBuild" @click="dialogFormVisible = true">新建</div>
                </div>
              </el-form-item>
              <div class="chooseCreationMethod" v-if="buildType == '0'">
                <span>基础镜像</span>
                <el-radio-group class="radios" v-model="baseImage">
                  <el-radio-button label="0">公有镜像</el-radio-button>
                  <el-radio-button label="1">私有镜像</el-radio-button>
                </el-radio-group>
              </div>
              <div class="obsCreationType" v-if="baseImage == '0' && buildType == '0'">
                <el-form-item prop="request.operating_system">
                  <el-select v-model="application.data.request.operating_system" clearable>
                    <el-option v-for="item in operating_system" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </div>
              <div class="obsCreationType" v-else-if="baseImage == '1' && buildType == '0'">
                <el-form-item prop="existed_image">
                  <el-select v-model="application.data.existed_image" class="m-2 fleet" clearable filterable placeholder="请输入IMS私有镜像名称进行筛选">
                    <el-option v-for="i in image_names" :key="i.value" :label="i.label" :value="i.value">
                      <div class="fleetLabel">{{ i.label }}</div>
                      <div class="fleetValue">{{ i.value }}</div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <el-form-item prop="request.storage_location.bucket_name" :rules="rules.bucket_name">
                <template #label>
                  <div class="item-label">obs桶</div>
                </template>
                <el-select
                  v-model="application.data.request.storage_location.bucket_name"
                  class="m-2 fleet"
                  clearable
                  filterable
                  placeholder="请输入obs桶名称进行筛选"
                >
                  <el-option v-for="i in bucket_names" :key="i.value" :label="i.label" :value="i.value"> </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="fileCreationType" v-if="creationMethod == '1'">
              <div class="file">
                <el-form-item prop="file">
                  <template #label>
                    <div class="item-label">上传应用包</div>
                  </template>
                  <el-upload
                    :class="fileValidate ? 'upload-demo' : 'upload-demo unvalid'"
                    ref="upload"
                    drag
                    action=""
                    :limit="1"
                    :auto-upload="false"
                    accept=".zip,.rar"
                    :file-list="fileList"
                    :on-change="handleChange"
                    :on-exceed="handleExceed"
                    :http-request="handleRequest"
                    :before-upload="beforeUpload"
                    :on-progress="handleProgress"
                    :show-file-list="false"
                  >
                    <template #trigger>
                      <div class="uploading" v-if="uploadState != 0">
                        <span>{{ files.data.name }}</span>
                      </div>
                      <div class="beforeUpload" v-if="uploadState == 0">
                        <span>点击上传文件或将文件拖拽至此</span><el-icon><FolderOpened /></el-icon>
                      </div>
                    </template>
                    <el-icon class="is-loading" v-if="uploadState == 2"><Loading /></el-icon>
                    <el-icon class="removing" v-if="uploadState == 1 || uploadState == 3" @click="onRemove"><Close /></el-icon>
                    <el-button class="btn new uploadButton" v-if="uploadState == 1" @click="onUpload">上传至obs桶</el-button>
                    <span class="loading" v-else-if="uploadState == 2"
                      >上传中，请勿刷新页面&nbsp;&nbsp;<span class="cancel" @click="cancelUpload">取消</span></span
                    >
                    <span class="loaded" v-else-if="uploadState == 3">上传成功！</span>
                    <template #tip>
                      <div class="el-upload__tip">仅支持上传一个文件，后缀格式限制为.zip,.rar</div>
                      <div v-if="!fileValidate" class="unvalid-error">请上传应用包文件</div>
                    </template>
                  </el-upload>
                </el-form-item>
              </div>
            </div>
            <div class="obsCreationType" v-else-if="creationMethod == '2'">
              <el-form-item prop="request.storage_location.bucket_key" :rules="rules.bucket_key">
                <template #label>
                  <div class="item-label">文件路径</div>
                </template>
                <el-input v-model="application.data.request.storage_location.bucket_key" maxlength="100" placeholder="示例：build_file/server-v1.zip" />
              </el-form-item>
            </div>
            <div class="obsCreationType" v-else-if="creationMethod == '3' && buildType == '0'">
              <el-form-item prop="existed_image" :rules="rules.existed_image">
                <template #label>
                  <div class="item-label">IMS私有镜像:</div>
                </template>
                <el-select v-model="application.data.existed_image" class="m-2 fleet" clearable filterable placeholder="请输入IMS私有镜像进行筛选">
                  <el-option v-for="i in image_names" :key="i.value" :label="i.label" :value="i.value">
                    <div class="fleetLabel">{{ i.label }}</div>
                    <div class="fleetValue">{{ i.value }}</div>
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="obsCreationType" v-else-if="creationMethod == '3' && buildType == '1'">
              <el-form-item prop="existed_image" :rules="rules.existed_image">
                <template #label>
                  <div class="item-label">SWR私有容器 :</div>
                </template>
                <el-select v-model="application.data.existed_image" class="m-2 fleet" clearable filterable placeholder="请输入SWR私有容器进行筛选">
                  <el-option v-for="i in mirror_image" :key="i.value" :label="i.label" :value="i.value">
                    <div class="fleetLabel">{{ i.label }}</div>
                    <div class="fleetValue">{{ i.value }}</div>
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div v-if="creationMethod != '3'">
            <div class="title">
              <div class="title-label"></div>
              配置用户权限
              <el-tooltip effect="dark" content="部署脚本将尝试创建用户，用户组进行绑定" placement="right">
                <el-icon><QuestionFilled /></el-icon
              ></el-tooltip>
            </div>
            <div class="formData">
              <el-form-item prop="request.user">
                <template #label>
                  <div class="item-label">用户</div>
                </template>
                <el-input v-model="application.data.request.user" maxlength="50" minlength="1" placeholder="用户" />
              </el-form-item>
              <el-form-item prop="request.group">
                <template #label>
                  <div class="item-label">所属用户组</div>
                </template>
                <el-input v-model="application.data.request.group" maxlength="50" placeholder="所属用户组" />
              </el-form-item>
              <el-form-item prop="request.user_password" :rules="rules.user_password">
                <template #label>
                  <div class="item-label">密码</div>
                </template>
                <el-input v-model="application.data.request.user_password" maxlength="50" placeholder="密码" />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <div class="operateButton">
        <el-button class="btn button" @click="onReset">重置</el-button>
        <el-button class="btn new button" type="primary" @click="onCreate">创建</el-button>
      </div>
    </div>
    <el-dialog v-model="dialogFormVisible" title="添加组织名称" width="20%">
      <el-form :model="form" :rules="rulesName" ref="ListRef">
        <el-form-item label="组织名称" :label-width="formLabelWidth" prop="organization" :rules="rulesName.organization">
          <el-input v-model.trim="form.organization" autocomplete="off" placeholder="请输入组织名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="btn button" @click="dialogFormVisible = false">取消</el-button>
          <el-button class="btn new button" type="primary" @click="onSubmitList(ListRef)"> 创建 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
  @import '@/assets/scss/dropdownBox.scss';
  .createApplication {
    .dialog-footer {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .create-appImage {
      height: 60px;
      width: calc(100% - 200px);
      position: absolute;
      top: 50px;
      left: 200px;
      background-color: $blank-color;
      color: $text-color;
      display: flex;
      align-items: center;
      z-index: 1;
      span {
        font-size: 16px;
        font-weight: bold;
        margin-left: 20px;
        margin-right: 21px;
        line-height: 60px;
      }
      .return {
        margin-left: 10px;
        color: #325cb0;
        font-size: 14px;
        font-weight: 700;
        cursor: pointer;
      }
      .region {
        margin-left: auto;
        margin-right: 40px;
        display: flex;
        align-items: center;
        span {
          margin-right: 7px;
          font-size: 14px;
          font-weight: normal;
        }
        .select {
          width: 140px;
        }
      }
    }
    .appImageMsg {
      background-color: $blank-color;
      margin-top: 60px;
      padding: 30px;
      .title {
        display: flex;
        align-items: center;
        margin-bottom: 36px;
        font-weight: bold;
        font-size: 14px;
        .title-label {
          width: 4px;
          height: 14px;
          background: #325cb0;
          border-radius: 0px;
          margin-right: 6px;
        }
      }
      .el-form-item {
        width: 620px;
        margin-bottom: 30px;
        :deep(.el-form-item__label) {
          display: inline-flex;
          align-items: center;
        }
        :deep(.el-form-item__label::before) {
          margin-left: -10px;
        }
      }
      .formData {
        margin-left: 10px;
        .description {
          .el-form-item {
            width: 940px;
          }
        }
        .chooseCreationMethod {
          display: flex;
          align-items: center;
          margin-bottom: 30px;
          span {
            font-size: 14px;
            width: 70px;
          }
          .radios {
            margin-left: 70px;
            :deep(.el-radio-button__inner) {
              width: 200px;
              height: 30px;
              border-radius: 2px;
              font-size: 14px;
              text-align: CENTER;
              color: #8a8e99;
            }
            :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
              background-color: #ecf2ff;
              border: 1px solid #325cb0;
              color: #325cb0;
              box-shadow: none;
            }
          }
        }
        .icon-outbox {
          .newBuild {
            width: 50px;
            height: 28px;
            margin-left: 20px;
            text-align: center;
            color: #ecf2ff;
            border: 1px solid #325cb0;
            background-color: #325cb0;
            border-radius: 2px;
            font-size: 14px;
            line-height: 28px;
            cursor: pointer;
          }
          .newBuild:hover {
            box-shadow: 0px 2px 2px $text-color;
          }
        }
        .fileCreationType {
          .file {
            .el-form-item {
              width: 100%;
              margin-bottom: 30px;
            }
          }
          .upload-demo,
          .unvalid {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            :deep(.el-upload-dragger) {
              width: 480px;
              border: 1px solid #e0e2e9;
              border-radius: 2px;
              padding: 0px;
              height: 30px;
            }
            :deep(.el-upload) {
              width: 480px;
              display: inline-flex;
            }
            .beforeUpload {
              height: 100%;
              font-size: 14px;
              font-family: Microsoft YaHei, Microsoft YaHei-Normal;
              text-align: LEFT;
              color: #b4b6be;
              line-height: 30px;
              padding-left: 10px;
              padding-right: 10px;
              display: flex;
              align-items: center;
              justify-content: space-between;
            }
            .uploading {
              height: 100%;
              font-size: 14px;
              padding-left: 10px;
              padding-right: 10px;
              line-height: 30px;
              display: flex;
              align-items: center;
              justify-content: space-between;
              color: #252b3a;
              font-family: Microsoft YaHei, Microsoft YaHei-Normal;
            }
            .is-loading {
              position: relative;
              left: -20px;
              top: 1px;
              margin-right: -14px;
            }
            .removing {
              position: relative;
              left: -40px;
              cursor: pointer;
              top: 1px;
              margin-right: -14px;
            }

            .uploadButton {
              height: 30px;
              font-size: 14px;
            }
            .loaded,
            .loading {
              margin-left: 10px;
              font-size: 14px;
              color: #b4b6be;
            }
            .cancel {
              margin-left: 10px;
              font-size: 14px;
              color: #325cb0;
              cursor: pointer;
            }
            :deep(.el-upload__tip) {
              margin-left: 10px;
              margin-top: 0px;
              color: #b4b6be;
              font-size: 14px;
              width: 100%;
            }
          }
          .unvalid {
            :deep(.el-upload-dragger) {
              width: 480px;
              border: 1px solid red;
              border-radius: 2px;
              padding: 0px;
              height: 30px;
            }
          }
          .unvalid-error {
            color: var(--el-color-danger);
            font-size: 12px;
            line-height: 1;
            padding-top: 2px;
            position: absolute;
            top: 100%;
            left: 0;
            width: 100%;
          }
        }
        .obsCreationType {
          .el-select {
            width: 280px;
          }
        }
      }
      .operateButton {
        .el-button + .el-button {
          margin-left: 0px;
        }
      }
    }
  }
</style>
<script lang="ts" setup>
  import appStore from '@/store'
  import { reactive, ref, watch } from 'vue'
  import type { FormInstance, FormRules, FormItemRule } from 'element-plus'
  import type { UploadInstance, UploadProps, UploadRawFile, UploadUserFile, UploadRequestOptions, UploadFile, UploadFiles } from 'element-plus'
  import { genFileId } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import ApplicationService, { uploadApp, createBuildRequest, uploadAppPath, controller, CreateBuildByImage, uploadAppImage } from '@/api/applicationService'
  import UserService from '@/api/userService'
  import router from '@/router'
  const dialogFormVisible = ref(false)
  const formLabelWidth = '100px'
  const ListRef = ref<FormInstance>()
  interface optionList {
    value: string
    label: string
  }
  let operating_system: optionList[] = reactive([])
  let dockerImages: optionList[] = reactive([])
  let organizationsGroup: optionList[] = reactive([])
  let bucket_names: optionList[] = reactive([])
  let image_names: optionList[] = reactive([])
  let mirror_image: optionList[] = reactive([])
  const creationMethod = ref('1')
  const buildType = ref('0')
  const baseImage = ref('0')
  const fileType = ['rar', 'zip']
  const createApplication = ref<FormInstance>()
  let files = reactive({ data: { name: '' } })
  let requestBody: createBuildRequest = reactive({
    name: '',
    description: '',
    version: '',
    user: '',
    group: '',
    user_password: '',
    bandwidth: {
      size: '',
      charging_mode: 'traffic'
    },
    build_type: '',
    operating_system_type: 0,
    operating_system: '',
    organization: '',
    storage_location: {
      bucket_name: '',
      bucket_key: ''
    },
    region: appStore.userStore.region
  })

  const application = reactive({
    data: {
      request: requestBody,
      file: files,
      existed_image: ''
    }
  })
  const olnyId = (rule: any, value: any, callback: any) => {
    let result = false
    organizationsGroup.forEach((item) => {
      if (item.label == value) {
        result = true
      }
    })
    if (value === '') {
      callback(new Error('组织名称为空'))
    } else if (result) {
      callback(new Error('组织名称重复'))
    } else {
      callback()
    }
  }
  const rulesName = reactive<FormRules>({
    organization: [
      { required: true, trigger: 'blur', validator: olnyId },
      {
        pattern: /^[a-z][a-z0-9]{0,63}$/,
        message: '组织名称 小写字母开头 允许小写字母数字',
        trigger: 'blur'
      }
    ]
  })
  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入应用包名称', trigger: 'blur' },
      { min: 2, message: '名称长度应在2-50范围内', trigger: 'blur' },
      {
        pattern: /^[a-z][\da-z_\-.]{1,49}$/,
        message: '应用包名 小写字母开头 允许小写字母数字下划线 中划线 点',
        trigger: 'blur'
      }
    ],
    version: [
      { required: true, message: '请输入版本号', trigger: 'blur' },
      {
        pattern: /^[a-z][\da-z_\-.]{1,49}$/,
        message: '版本号 小写字母开头 允许小写字母数字下划线 中划线 点',
        trigger: 'blur'
      }
    ],

    vpc_id: [{ required: true, message: '选择VPC', trigger: 'blur' }],
    subnet_id: [{ required: true, message: '选先择VPC再选择Subnet', trigger: 'blur' }],
    bucket_name: [{ required: true, message: '请选择obs桶', trigger: 'blur' }],
    bucket_key: [{ required: true, message: '请输入文件路径', trigger: 'blur' }],
    file: [{ required: true }],
    charging_mode: [{ required: true, message: '请选择带宽计费方式', trigger: ['change', 'blur'] }],
    organization: [{ required: true, message: '请选择指定组织', trigger: ['change', 'blur'] }],
    operating_system: [{ required: true, message: '请选择基础镜像', trigger: ['change', 'blur'] }],
    existed_image: [{ required: true, message: '请选择IMS镜像', trigger: 'blur' }],
    user_password: [
      { required: false, message: '请输入密码', trigger: 'blur' },
      {
        pattern: /^[a-zA-Z\d.-_=@#]{8,20}$/,
        message: '以"大小写字母,数字 . - = _ @ #"组成',
        trigger: 'blur'
      }
    ],
    bandwidth: [
      {
        type: 'number',
        min: 1,
        max: 2000,
        required: true,
        message: '请输入1-2000范围内的数字',
        trigger: ['change', 'blur']
      }
    ]
  })

  const fileList = ref<UploadUserFile[]>([])
  const upload = ref<UploadInstance>()
  let uploadState = ref(0)
  let fileValidate = ref(true)
  watch(uploadState, (newvalue, oldvalue) => {
    if (newvalue == 3) {
      fileValidate.value = true
    }
  })

  let uploadAPP: uploadApp = {
    project_id: appStore.userStore.project_id,
    file: new FormData()
  }

  let createApp: uploadAppPath = {
    project_id: appStore.userStore.project_id,
    CreateBuildRequest: requestBody
  }
  let createBuildbyImage: CreateBuildByImage = {
    name: '',
    description: '',
    version: '',
    region: '',
    image_id: '',
    build_type: ''
  }

  let createAppbyImage: uploadAppImage = {
    project_id: appStore.userStore.project_id,
    CreateBuildByImageRequest: createBuildbyImage
  }

  const getbucket = {
    project_id: appStore.userStore.project_id,
    region: appStore.userStore.region,
    vpc_id: '',
    user_password: ''
  }
  const form = reactive({
    project_id: appStore.userStore.project_id,
    organization: '',
    region: appStore.userStore.region
  })
  const onSubmitList = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        let createOrganizatio
        createOrganizatio = JSON.parse(JSON.stringify(form))
        try {
          let res = await ApplicationService.uploadOrganization(createOrganizatio)
          if (res.status < 300) {
            organizationsGroup.length = 0
            ElMessage({
              message: '创建成功',
              type: 'success'
            })
            dialogFormVisible.value = false
            form.organization = ''
            let obj = {
              label: res.data.organization,
              value: res.data.organization
            }
            organizationsGroup.push(obj)
            getOrganization()
          }
        } catch (err) {
          ElMessage.error('创建失败')
        }
      } else {
        ElMessage({
          message: '请检查参数',
          type: 'warning'
        })
      }
    })
  }
  const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
  }

  const handleChange: UploadProps['onChange'] = (uploadFile: UploadFile, uploadFiles) => {
    if (uploadFile.status == 'ready' && uploadState.value !== 2) {
      uploadState.value = 1
    }
    if (uploadFile.status === 'fail' || uploadFile.status === 'success') {
      upload.value!.clearFiles()
      upload.value!.handleStart(uploadFiles[0].raw as UploadRawFile)
    }
    files.data = uploadFile
  }
  let tempStorage_location = { bucket_key: '', bucket_name: '' }
  const onRemove = () => {
    upload.value!.clearFiles()
    uploadState.value = 0
    tempStorage_location = {
      bucket_key: '',
      bucket_name: ''
    }
    controller.abort()
    ApplicationService.updateController()
  }
  const onReset = () => {
    createApplication.value?.resetFields()
    fileValidate.value = true
    if (creationMethod.value == '1') {
      onRemove()
    }
  }
  const cancelUpload = () => {
    controller.abort()
    ApplicationService.updateController()
    uploadState.value = 1
  }

  const beforeUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) => {
    var FileExt = rawFile.name.replace(/.+\./, '')
    if (fileType.indexOf(FileExt.toLowerCase()) === -1) {
      ElMessage({
        message: '上传的文件必须是rar、zip类型',
        type: 'error'
      })
      return false
    }
    return true
  }

  const onUpload = async () => {
    let formValid = await createApplication.value?.validateField('request.storage_location.bucket_name', (valid) => {
      return valid
    })
    if (formValid) {
      upload.value!.submit()
    }
  }
  const uploadfile = async () => {
    try {
      uploadState.value = 2
      let res = await ApplicationService.uploadApplication(uploadAPP)
      if (res.status === 200) {
        uploadState.value = 3
        tempStorage_location.bucket_key = res.data.bucket_key
        tempStorage_location.bucket_name = res.data.bucket_name
      }
    } catch (err) {
      uploadState.value = 1
    }
  }
  const handleRequest = async (option: UploadRequestOptions) => {
    let { file } = option
    let formData = new FormData()
    formData.append('file', file)
    formData.append('region', appStore.userStore.region)
    formData.append('bucket_name', application.data.request.storage_location.bucket_name)
    uploadAPP.file = formData
    uploadfile()
  }

  const handleProgress = () => {
    uploadState.value = 2
  }
  let creating = ref(false)
  const onCreatebyImage = async () => {
    try {
      createAppbyImage.CreateBuildByImageRequest.description = application.data.request.description
      createAppbyImage.CreateBuildByImageRequest.name = application.data.request.name
      createAppbyImage.CreateBuildByImageRequest.version = application.data.request.version
      createAppbyImage.CreateBuildByImageRequest.region = appStore.userStore.region
      createAppbyImage.CreateBuildByImageRequest.image_id = application.data.existed_image
      if (buildType.value == '0') {
        createAppbyImage.CreateBuildByImageRequest.build_type = 'VM'
      } else {
        createAppbyImage.CreateBuildByImageRequest.build_type = 'POD'
      }
      creating.value = true
      let res = await ApplicationService.uploadApplicationImage(createAppbyImage)
      if (res.status === 200) {
        creating.value = false
        ElMessage({
          message: '创建成功！',
          type: 'success'
        })
        router.push({
          name: 'applicationList'
        })
      }
    } catch (error) {
      creating.value = false
      ElMessage.error('创建失败')
    }
  }
  const onCreatebyOthers = async () => {
    try {
      if (creating.value) return
      createApp.CreateBuildRequest = JSON.parse(JSON.stringify(application.data.request))
      if (creationMethod.value == '1') {
        createApp.CreateBuildRequest.storage_location.bucket_key = tempStorage_location.bucket_key
        createApp.CreateBuildRequest.storage_location.bucket_name = tempStorage_location.bucket_name
      }
      if (creationMethod.value == '2') {
        createApp.CreateBuildRequest.storage_location.bucket_key = application.data.request.storage_location.bucket_key
        createApp.CreateBuildRequest.storage_location.bucket_name = application.data.request.storage_location.bucket_name
      }
      creating.value = true
      let res = await ApplicationService.uploadApplicationPath(createApp)
      if (res.status === 200) {
        creating.value = false
        ElMessage({
          message: '创建成功！',
          type: 'success'
        })
        router.push({
          name: 'applicationList'
        })
      }
    } catch (error) {
      creating.value = false
      ElMessage.error('创建失败')
    }
  }
  const onCreate = async () => {
    try {
      if (creating.value) return
      let formValid = await createApplication.value?.validate((valid) => {
        return valid
      })

      if (creationMethod.value == '1' && uploadState.value !== 3) {
        fileValidate.value = false
        return
      }
      if (baseImage.value == '0') {
        application.data.request.operating_system_type = 0
      } else {
        application.data.request.operating_system_type = 1
      }
      if (buildType.value == '0') {
        application.data.request.build_type = 'VM'
      } else {
        application.data.request.build_type = 'POD'
      }
      if (formValid) {
        if (creationMethod.value == '3') {
          onCreatebyImage()
        } else {
          onCreatebyOthers()
        }
      }
    } catch (error) {
      creating.value = false
      ElMessage.error('创建失败')
    }
  }

  const getBucketName = async () => {
    let res = await UserService.getBucket(getbucket)
    if (res.status == 200) {
      res.data.bucket_name.forEach((item: string) => {
        bucket_names.push({
          value: item,
          label: item
        })
      })
    }
  }

  const goback = () => {
    router.push({
      name: 'applicationList'
    })
  }

  const getImageName = async () => {
    let res = await UserService.getImageList(getbucket)
    if (res.status == 200) {
      res.data.image_list.forEach((item: any) => {
        image_names.push({
          value: item.image_id,
          label: item.image_name
        })
      })
    }
  }

  const getMirrorImage = async () => {
    let res = await UserService.getMirrorImage(getbucket)
    if (res.status == 200) {
      res.data.docker_image_list.forEach((item: any) => {
        mirror_image.push({
          value: item,
          label: item
        })
      })
    }
  }

  const getDockerImage = async () => {
    let res = await UserService.getDockerImage(getbucket)
    if (res.status == 200) {
      res.data.support_image_list.forEach((item: any) => {
        dockerImages.push({
          value: item,
          label: item
        })
      })
    }
  }

  const getOrganization = async () => {
    let res = await UserService.getOrganization(getbucket)
    if (res.status == 200) {
      res.data.forEach((item: any) => {
        organizationsGroup.push({
          value: item,
          label: item
        })
      })
    }
  }
  const getOperatingSystem = async () => {
    let res = await UserService.getSystem(getbucket)
    if (res.status == 200) {
      res.data.support_image_list.forEach((item: any) => {
        operating_system.push({
          label: item,
          value: item
        })
      })
    }
  }

  let vpcOptions: optionList[] = reactive([])
  let subnetOptions: optionList[] = reactive([])
  const getSubnetName = async (id: any) => {
    getbucket.vpc_id = id
    let res = await UserService.getSubnetList(getbucket)
    if (res.status == 200) {
      subnetOptions.length = 0
      res.data.subnet_list.forEach((item: any) => {
        subnetOptions.push({
          value: item.subnet_id,
          label: item.subnet_name
        })
      })
    }
  }
  const vpcChange = (val: any) => {
    if (val) {
      getSubnetName(val)
    }
  }
  const getVpcName = async () => {
    let res = await UserService.getVpcList(getbucket)
    if (res.status == 200) {
      vpcOptions.length = 0
      res.data.vpc_list.forEach((item: any) => {
        vpcOptions.push({
          value: item.vpc_id,
          label: item.vpc_name
        })
      })
    }
  }

  getImageName()
  getBucketName()
  getOperatingSystem()
  getDockerImage()
  getVpcName()
  getOrganization()
  getMirrorImage()
</script>
